package com.googlecode.restitory.gae.filter.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.fileupload.FileItem;

public class FileItemImpl implements FileItem {

	private static final long serialVersionUID = -5220718646739539920L;

	private String fieldName;
	private final String contentType;
	private boolean isFormField;
	private final String fileName;

	private ByteArrayOutputStream out = new ByteArrayOutputStream();

	public FileItemImpl(String fieldName, String contentType, boolean isFormField, String fileName) {
		this.fieldName = fieldName;
		this.contentType = contentType;
		this.isFormField = isFormField;
		this.fileName = fileName;
	}

	@Override
	public InputStream getInputStream() throws IOException {
		return new ByteArrayInputStream(out.toByteArray());
	}

	@Override
	public String getContentType() {
		return contentType;
	}

	@Override
	public String getName() {
		return fileName;
	}

	@Override
	public boolean isInMemory() {
		return true;
	}

	@Override
	public long getSize() {
		return out.toByteArray().length;
	}

	@Override
	public byte[] get() {
		return out.toByteArray();
	}

	@Override
	public String getString(String encoding) throws UnsupportedEncodingException {
		return ContentUtil.getString(get(), encoding);
	}

	@Override
	public String getString() {
		throw new RuntimeException("unsupported");
	}

	@Override
	public void write(File file) throws Exception {
		throw new RuntimeException("unsupported");
	}

	@Override
	public void delete() {
		throw new RuntimeException("unsupported");
	}

	@Override
	public String getFieldName() {
		return fieldName;
	}

	@Override
	public void setFieldName(String name) {
		this.fieldName = name;
	}

	@Override
	public boolean isFormField() {
		return isFormField;
	}

	@Override
	public void setFormField(boolean state) {
		this.isFormField = state;
	}

	@Override
	public OutputStream getOutputStream() throws IOException {
		return out;
	}

	@Override
	public String toString() {
		return "FileItemImpl [fieldName=" + fieldName + ", contentType=" + contentType + ", isFormField=" + isFormField
				+ ", fileName=" + fileName + ", length=" + getSize() + "]";
	}

}
